package com.tqyan.start.controller;

import com.alibaba.fastjson.JSONObject;
import com.tqyan.model.controller.request.OpenAIChatRequest;
import com.tqyan.model.controller.response.OpenAIChatResp;
import com.tqyan.model.enums.ChatCreativeAbilityEnum;
import com.tqyan.model.enums.GPTModelEnum;
import com.tqyan.model.enums.GPTRoleEnum;
import com.tqyan.service.service.SoundService;
import com.tqyan.service.transfer.FileService;
import com.tqyan.service.transfer.OpenAIService;
import com.tqyan.service.service.impl.SoundServiceImpl;
import com.tqyan.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Autowired
    private FileService fileService;
    @Autowired
    private SoundService soundService;
    @Autowired
    private OpenAIService openAIService;

    @RequestMapping("/getInfo")
    public Object getInfo() {
        return DateUtil.format(DateUtil.now(), DateUtil.DATE_LONG);
    }

    @RequestMapping("/http")
    public Object http(@RequestBody String key) {
//        Map<String, String> headers = new HashMap<>();
//        headers.put("Accept", "*/*");
//        headers.put("Accept-Encoding", "gzip, deflate, br");
//        headers.put("Connection", "keep-alive");
//        headers.put("Content-Type", "application/json");
//        headers.put("Authorization", "Bearer " + key);
//        try {
//            OpenAIChatRequest request = new OpenAIChatRequest();
//            request.setModel(GPTModelEnum.GPT_3_5.getValue());
//            request.setTemperature(ChatCreativeAbilityEnum.TEMPERATURE_1_0.getTemperature() / 10D);
//            request.setStream(true);
//            request.addMessage(GPTRoleEnum.USER.getValue(), "给我一个启发");
//
//            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//            // 创建http对象
//            HttpPost httpPost = new HttpPost(OpenAIService.URL_CHAT);
//            for (Map.Entry<String, String> entry : headers.entrySet()) {
//                httpPost.setHeader(entry.getKey(), entry.getValue());
//            }
//            StringEntity entity = new StringEntity(OpenAIChatRequest.getRequestBody(request)
//                    , ContentType.APPLICATION_JSON);
//            httpPost.setEntity(entity);
//            // 执行请求并获得响应结果
//            HttpResponse httpResponse = httpClient.execute(httpPost);
//            InputStream inputStream = httpResponse.getEntity().getContent();
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//            String line;
//            log.info("=========================================");
//            while ((line = bufferedReader.readLine()) != null) {
//                log.info(line);
//            }
//            log.info("=========================================");
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//        }
        return DateUtil.format(DateUtil.now(), DateUtil.DATE_LONG);
    }

//    @RequestMapping("/download/{fileName}")
//    public Object download(HttpServletResponse response, @PathVariable String fileName) {
//        try {
//            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
//            fileService.downloadAliyunOSS(response.getOutputStream(), FileService.FOLDER_DRAW, fileName);
//            return null;
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }

//    @PostMapping("/upload")
//    public Object handleFileUpload(@RequestParam("file") MultipartFile file) {
//        try {
//            return soundService.soundDictation(null, fileService.convertUploadFile(file));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }

//    @RequestMapping("/dataShadow")
//    public Object dataShadow(@RequestBody String requestBody) {
//        try {
//            JSONObject request = JSONObject.parseObject(requestBody);
//            String name = request.getString("name");
//            String roleDescription = request.getString("roleDescription");
//            String roleAnswer = request.getString("roleAnswer");
//            String question = request.getString("question");
//
//            long beginTime = System.currentTimeMillis();
//            OpenAIChatRequest chatRequest = new OpenAIChatRequest();
//            chatRequest.setModel(GPTModelEnum.GPT_3_5.getValue());
//            chatRequest.setTemperature(1.0);
//            chatRequest.addMessage(GPTRoleEnum.USER.getValue(), question);
//            chatRequest.addMessage(GPTRoleEnum.USER.getValue(), "以下问题请围绕“" + roleAnswer + "”来进行回答，并在回答前简单的介绍一下自己");
//            chatRequest.addMessage(GPTRoleEnum.USER.getValue(), "你现在是：" + roleDescription);
//            log.info("[设置会话内容关键词] chatRequest{}, 请求GPT", chatRequest);
//            OpenAIChatResp chatResp = openAIService.requestChatComplete(chatRequest);
//            long endTime = System.currentTimeMillis();
//            log.info("[设置会话内容关键词] chatRequest{}, chatResp={}, 请求GPT。耗时: {}ms"
//                    , chatRequest, chatResp, endTime - beginTime);
//            String result = "你好，我是" + name + "。很荣幸将由我来回答你的问题。\n\n";
//            return result + chatResp.getChoices().get(0).getMessage().getContent();
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return e.getMessage();
//        }
//    }

}


